package com.example.demo.controller;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@RestController
public class FileController {
    private static final String UPLOADED_FOLDER = System.getProperty("user.dir") + "\\upload\\";

    @PostMapping("/up")
    public String upload(String nickname, MultipartFile file, HttpServletRequest request) throws IOException {
        System.out.println("文件大小：" + file.getSize());
        System.out.println("文件类型：" + file.getContentType());
        System.out.println("原文件名：" + file.getOriginalFilename());
        String path = request.getServletContext().getRealPath("/upload/");
        System.out.println(path);

        saveFile(file, path);
        // 检查文件是否为空
        return "上传成功";
    }

    public void saveFile(MultipartFile f, String path) throws IOException {
        File upDir = new File(path);
        if (!upDir.exists()) {
            upDir.mkdir();
        }
        File file = new File(path + f.getOriginalFilename());
        f.transferTo(file);
    }
}
